﻿using System;
using System.Web.Script.Serialization;
using TCPServer.script.proto;

public class MsgBase
{
    //协议名
    public string protoName = "";

    //编码器
    private static JavaScriptSerializer Js = new JavaScriptSerializer();

    //编码
    public static byte[] Encode(MsgBase msgBase)
    {
        string s = Js.Serialize(msgBase);
        return System.Text.Encoding.UTF8.GetBytes(s);
    }

    //解码
    public static MsgBase Decode(string protoName, byte[] bytes, int offset, int count)
    {
        string s = System.Text.Encoding.UTF8.GetString(bytes, offset, count);
        Type type = Type.GetType(protoName);
        MsgBase msg = (MsgBase)Js.Deserialize(s, type);
        return msg;
    }

    //编码协议名
    public static byte[] EncodeName(MsgBase msgBase)
    {
        byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(msgBase.protoName);
        Int16 length = (Int16)nameBytes.Length;
        byte[] bytes = new byte[2 + length];
        bytes[0] = (byte)(length % 256);//以小端形式编码协议名长度
        bytes[1] = (byte)(length / 256);
        nameBytes.CopyTo(bytes, 2);
        Array.Copy(nameBytes, 0, bytes, 2, length);
        return bytes;
    }

    //解码协议名
    public static string DecodeName(byte[] bytes, int offset, out int count)
    {
        count = 0;
        if (offset + 2 > bytes.Length)
        {
            return "";
        }
        Int16 len = (Int16)((bytes[offset + 1] << 8) | bytes[offset]);
        if (len <= 0)
        {
            return "";
        }
        if (offset + 2 + len > bytes.Length)
        {
            return "";
        }
        count = 2 + len;
        string s = System.Text.Encoding.UTF8.GetString(bytes, offset + 2, len);
        return s;
    }
}